<?php
namespace ObjectStorage\Adapters;

use ChatX\Storage\Driver;
use Qcloud\Cos\Client;
use Qcloud\Cos\Exception\ServiceResponseException;

class CosAdapter implements Driver
{
    /**
     * @var Client|null
     */
    private $client;

    /**
     * {@Liuguobo}
     */
    public function connect(array $config): bool
    {
        try {
            $this->client = new Client([
                'region' => $config['region'] ?? '',
                'schema' => $config['schema'] ?? 'https',
                'credentials' => [
                    'secretId' => $config['secret_id'] ?? '',
                    'secretKey' => $config['secret_key'] ?? ''
                ]
            ]);

            return true;
        } catch (\Exception $e) {
            error_log("腾讯云COS连接失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function upload(string $bucket, string $objectKey, string $filePath, array $options = [])
    {
        if (!$this->client || !file_exists($filePath)) {
            return false;
        }

        try {
            $result = $this->client->putObject([
                'Bucket' => $bucket,
                'Key' => $objectKey,
                'Body' => fopen($filePath, 'rb'),
                'ContentType' => $options['content_type'] ?? mime_content_type($filePath)
            ]);

            return [
                'success' => true,
                'etag' => $result['ETag'] ?? '',
                'location' => $result['Location'] ?? '',
                'object_key' => $objectKey
            ];
        } catch (ServiceResponseException $e) {
            error_log("腾讯云COS上传失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function download(string $bucket, string $objectKey, string $savePath, array $options = []): bool
    {
        if (!$this->client) {
            return false;
        }

        try {
            $result = $this->client->getObject([
                'Bucket' => $bucket,
                'Key' => $objectKey
            ]);

            file_put_contents($savePath, $result['Body']);
            return file_exists($savePath);
        } catch (ServiceResponseException $e) {
            error_log("腾讯云COS下载失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function delete(string $bucket, string $objectKey): bool
    {
        if (!$this->client) {
            return false;
        }

        try {
            $this->client->deleteObject([
                'Bucket' => $bucket,
                'Key' => $objectKey
            ]);

            return true;
        } catch (ServiceResponseException $e) {
            error_log("腾讯云COS删除失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function getInfo(string $bucket, string $objectKey)
    {
        if (!$this->client) {
            return false;
        }

        try {
            $result = $this->client->headObject([
                'Bucket' => $bucket,
                'Key' => $objectKey
            ]);

            return [
                'content_type' => $result['ContentType'] ?? '',
                'size' => $result['ContentLength'] ?? 0,
                'last_modified' => $result['LastModified'] ?? null,
                'etag' => $result['ETag'] ?? ''
            ];
        } catch (ServiceResponseException $e) {
            error_log("腾讯云COS获取信息失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function getUrl(string $bucket, string $objectKey, int $expires = 3600)
    {
        if (!$this->client) {
            return false;
        }

        try {
            $url = $this->client->getObjectUrl($bucket, $objectKey, time() + $expires);
            return $url;
        } catch (ServiceResponseException $e) {
            error_log("腾讯云COS生成URL失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function listObjects(string $bucket, array $options = [])
    {
        if (!$this->client) {
            return false;
        }

        try {
            $params = [
                'Bucket' => $bucket
            ];

            if (!empty($options['prefix'])) {
                $params['Prefix'] = $options['prefix'];
            }

            if (!empty($options['max_keys'])) {
                $params['MaxKeys'] = $options['max_keys'];
            }

            $result = $this->client->listObjectsV2($params);
            return $result['Contents'] ?? [];
        } catch (ServiceResponseException $e) {
            error_log("腾讯云COS列出对象失败: " . $e->getMessage());
            return false;
        }
    }
}
